from rest_framework.views import APIView
from rest_framework.response import Response
from meiduo_mall.utils.qq_sdk import OAuthQQ
from users.models import User
from .models import OAuthQQUser
from meiduo_mall.utils import jwt_token
from .serializers import OAuthQQUserSerializer
from rest_framework import generics
from carts.utils import merge_cookie_to_redis
#  url(r'^qq/authorization/$', views.QQAuthURLView.as_view()),
class QQAuthUserView(APIView):
    """
    获取QQ登录的url
    """
    def get(self, request):
        """
        提供用于qq登录的url
        """
        #获取客户端的next参数
        state = request.query_params.get('next')
        oauth = OAuthQQ(state=state)
        #获取qq的登录地址
        login_url = oauth.get_qq_login_url()
        #响应
        return Response({'login_url': login_url})



class QQAuthOpenIdView(generics.CreateAPIView):

    def get(self,request):
        #获取code
        code = request.query_params.get('code')

        try:

            #与QQ服务器进行交互
            oauthqq = OAuthQQ()
            #通过code获取token
            token=oauthqq.get_access_token(code)
            #通过token获取openid
            openid=oauthqq.get_openid(token)

        except:
            return Response({'message':'访问QQ服务器失败'})

        #查询是否绑定现有帐号
        try:
            qq = OAuthQQUser.objects.get(openid=openid)
        except:
            #查询未绑定，返回绑定页面
            #加密
            access_token=OAuthQQ.generate_openid_token(openid)
            #响应
            return Response({'access_token':access_token})
        else:
            #查询已经绑定了，状态保持，返回首页
            #生成jwt
            token = jwt_token.get_token(qq.user)

            response = Response({
                'user_id': qq.user.id,
                'username': qq.user.username,
                'token': token,
            })
            #合并

            response = merge_cookie_to_redis(request,qq.user,response)


            #响应
            return response

        return Response(openid)

    def post(self, request):
       #将openid与本网站帐号绑定
       #1.接受数据
        # request.data

        response = super().post(request)
        if 'user_id' in response.data:
            user = User.objects.get(pk=response.data.get('user_id'))
            response = merge_cookie_to_redis(request,user,response)
    serializer_class = OAuthQQUserSerializer
